import numpy as np
import cv2
from rknn.api import RKNN
from PIL import Image
import psutil 
import time
# Model from https://github.com/airockchip/rknn_model_zoo
ONNX_MODEL = 'mnist.onnx'
RKNN_MODEL = 'mnist.rknn'
IMG_PATH = './1.png'
DATASET = './dataset.txt'

QUANTIZE_ON = True
IMG_SIZE = 28

#模型的类别
CLASSES = ("0", "1", "2", "3 ", "4 ", "5 ","6", "7", "8 ", "9 ")

def show_outputs(output):
    output_sorted = sorted(output, reverse=True)
    top5_str = '\n-----TOP 5-----\n'
    for i in range(5):
        value = output_sorted[i]
        index = np.where(output == value)
        for j in range(len(index)):
            if (i + j) >= 5:
                break
            if value > 0:
                topi = '{}: {:.2f}%\n'.format(index[j], value*100)
            else:
                topi = '-1: 0.0\n'
            top5_str += topi
    print(top5_str)

def softmax(x):
    return np.exp(x)/sum(np.exp(x))

if __name__ == '__main__':

    # Create RKNN object
    rknn = RKNN(verbose=True)

    # pre-process config
    print('--> Config model')
    rknn.config(mean_values=None, std_values=None, target_platform='rk3568')#mean_values=[0.1307], std_values=[0.3081]
    print('done')

    # Load ONNX model
    print('--> Loading model')
    ret = rknn.load_onnx(model=ONNX_MODEL)
    if ret != 0:
        print('Load model failed!')
        exit(ret)
    print('done')

    # Build model
    print('--> Building model')
    ret = rknn.build(do_quantization=QUANTIZE_ON, dataset=DATASET) 
    if ret != 0:
        print('Build model failed!')
        exit(ret)
    print('done')

    # Export RKNN model
    print('--> Export rknn model')
    ret = rknn.export_rknn(RKNN_MODEL)
    if ret != 0:
        print('Export rknn model failed!')
        exit(ret)
    print('done')

    # Init runtime environment
    print('--> Init runtime environment')
    ret = rknn.init_runtime()
    if ret != 0:
        print('Init runtime environment failed!')
        exit(ret)
    print('done')

    # Set inputs
    img = cv2.imread(IMG_PATH)
    print(img.shape)
    img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))
    img=img.reshape(1, 28, 28, 1)# (b)
    print(img.shape) #(1, 28, 28, 1)

    # Inference
    print('--> Running model')

    # 记录开始时间  
    start_time = time.time()
    outputs = rknn.inference(inputs=[img])
    # 记录结束时间  
    end_time = time.time()

    # np.save('./onnx_mnist_0.npy', outputs[0])
    print(softmax(np.array(outputs[0][0])))
    show_outputs(softmax(np.array(outputs[0][0])))
    print('done')
    print("===============输出数据形状========================")
    print(outputs[0].shape) # (1,10)
    # 计算推理时间  
    inference_time = end_time - start_time  
    print("===============模型推理时间========================")
    print("Inference time:", inference_time, "seconds")

    rknn.release()
